<?php
/**
 * Description: 行测 - 智能组卷作业模块
 * User: devforma
 * Date: 16/5/26
 * Time: 12:05
 */

require __DIR__ . '/ProcessExerciseBase.class.php';

class XingcezhinengModule extends ProcessExerciseBase {
    private $noteHierarchy;

    function __construct($exerciseType) {
        parent::__construct();
        $this->data['exercise_type'] = (int)$exerciseType;
    }

    /**
     * 设置作业类型
     */
    protected function setExerciseType() {
        return;
    }

    /**
     * 设置作业题目
     */
    protected function setExerciseQuestion() {

        //获取所有真题
        $list = getQuestionsByIds($this->questionIds);

        foreach ($list as &$l) {

            //行测智能笔记
            $question_notes = getQuestionNotes(['user_id' => $this->userId,'question_id' => $l['id']]);

            $l['question_id']       = $l['id'];
            $l['question_notes']    = !empty($question_notes) ? $question_notes->content : '';

            unset($l['id']);
        }
        $this->data['question']    = $list;

        //设置课程课堂名
        $this->data['course_name'] = !empty($this->exerciseInfo->course_id) ? $this->getCourseName($this->exerciseInfo->course_id) : '';
        $this->data['class_name']  = !empty($this->exerciseInfo->class_id) ? $this->getClassName($this->exerciseInfo->class_id): '';
    }

    /**
     * 设置默认答题记录--旧数据读取时  当答案为空时执行
     */
    protected function setDefaultInfoByXingcezhineng() {
        global $uddb;

        $insertList = [];
        foreach ($this->data['question'] as $k => &$q) {
            if(empty($q['user_answer'])){

                $user_answer = [
                    'question_id' => $q['question_id'],
                    'is_collected'=> false,
                    'is_right'    => false,
                    'action_time' => $this->now,
                    'answer'      => ''
                ];
                $q['user_answer'] = $user_answer;

                $insertList[] = [
                    'user_id'     => $this->userId,
                    'question_id' => $q['question_id'],
                    'note_id'     => $q['note_id'],
                    'exercise_id' => $this->exerciseId,
                    'testarea_id' => 1126, //按照国考处理
                    'category_id' => $q['category_id'],
                    'user_answer' => '',
                    'is_right'    => false,
                    'test_time'   => $this->now
                ];
            }
        }

        if (!empty($insertList)) {
            $uddb->usertestsTable($this->userId)->batchInsert($insertList);
        }

    }

    /**
     * 设置提交权限
     */
    protected function setSubmitPriv() {
        parent::setSubmitPriv();
    }

    /**
     * 设置用户答案
     */
    protected function setUserAnswer() {
        global $uddb;

        //查询用户做题记录
        $records = (array)$uddb->usertestsTable($this->userId)->where(array('user_id' => $this->userId, 'exercise_id' => $this->exerciseId))->get();
        
        if (!empty($records)) {
            $answers = array();
            foreach ($records as $q) {

                $answers[$q->question_id] = array(
                    'question_id'   => (int)$q->question_id,
                    'is_right'      => (bool)$q->is_right,
                    'is_collected'  => $q->is_collected == 1,
                    'action_time'   => $q->test_time,
                    'answer'        => $q->user_answer
                );
            }

            $this->data['user_answer'] = $answers;
        }
        //需要进行题目答案的合并
        $this->shouldMergeQA = true;
    }


    /**
     * 设置作业的统计信息
     */
    protected function setSummary() {

        //查询用户提交作业的统计信息
        $summary = $this->userExerciseRecord->summary;

        if (!empty($summary) && ($summary = json_decode($summary))) {

            //获取知识点结构
            $this->noteHierarchy = getNewNoteHierarchy();

            $categorys = [];
            foreach ($summary->note_info as $index => &$note) {
                $note->id         = (int)$note->id;
                $note->duration   = round($note->duration, 1);
                $note->name       = $this->noteHierarchy[$note->id]['name'];

                //查找该知识点的科目
                if (isset($this->noteHierarchy[$note->id])) {
                    $category = $this->findNoteRoot($this->noteHierarchy[$note->id]);

                    if (isset($categorys[$category['id']])) { //已经存在该科目
                        $categorys[$category['id']]['notes'][] = $note;
                        $categorys[$category['id']]['total'] += $note->total;
                        $categorys[$category['id']]['right'] += $note->right;
                        $categorys[$category['id']]['duration'] += $note->duration;
                    } else {                                  //该科目首次出现
                        $categorys[$category['id']] = [
                            'id'       => (int)$category['id'],
                            'name'     => $this->noteHierarchy[$category['id']]['name'],
                            'notes'    => [$note],
                            'total'    => $note->total,
                            'right'    => $note->right,
                            'duration' => $note->duration
                        ];
                    }
                }
            }

            $summary->position      = (int)$summary->position;
            $summary->duration      = (int)$summary->duration;
            $summary->accuracy      = (float)$summary->accuracy;
            $summary->category_info = array_values($categorys);

            $this->data['summary'] = $summary;
        }
    }

    /**
     * 根据知识点查找科目
     *
     * @param object $note 知识点
     * @return object
     */
    private function findNoteRoot($note) {
        if (isset($this->noteHierarchy[$note['parent_id']])) {
            return $this->findNoteRoot($this->noteHierarchy[$note['parent_id']]);
        }

        return $note;
    }

    /**
     * 检测提交的参数
     * @param array $args 参数
     * @return bool
     */
    public function validateArgs($args) {
        if (!empty($args['answer_content']) && !empty($args['duration'])) {
            $this->submitArgs = $args;
            return true;
        }

        return false;
    }

    /**
     * 提交 - 设置作业状态
     */
    protected function setSubmitStatus() {
        if ($this->exerciseInfo->end_time > $this->now)
            $this->submitExerciseRecord['status'] = 1; //已完成
        else
            $this->submitExerciseRecord['status'] = 5; //过期完成
    }

    /**
     * 提交 - 保存答题记录及设置作业统计信息
     */
    protected function saveQuestionRecordsAndSetSubmitSummary() {
        global $uddb;

        $answers = json_decode($this->submitArgs['answer_content']);

        $insertList = array(); //待入表的数据记录
        $notes      = array(); //知识点统计信息
        $qSummary   = array(); //单题统计信息
        $total = $right = 0;   //题目总数和答对数
        foreach ($answers as $q) {
            $total++;

            //题目统计
            $qSummary[] = array(
                $q->id,             //题目id
                (int)$q->is_right,  //是否正确
                $q->duration,       //答题时间
                $q->answer,         //用户选项
            );

//            if (empty($q->answer)) continue;

            $insertList[] = array(
                'user_id'     => $this->userId,
                'question_id' => $q->id,
                'note_id'     => $q->note_ids[0],
                'exercise_id' => $this->exerciseId,
                'testarea_id' => 1126, //按照国考处理
                'category_id' => $q->category,
                'user_answer' => $q->answer,
                'is_right'    => $q->is_right,
                'test_time'   => $this->now
            );

            if ($q->is_right) $right++;

            //统计知识点答题情况
            foreach ($q->note_ids as $noteId) {
                if (!isset($notes[$noteId])) {
                    $notes[$noteId] = array('id' => $noteId,'total' => 0, 'right' => 0, 'duration' => 0);
                }

                $notes[$noteId]['duration'] += $q->duration; //知识点答题总时间
                $notes[$noteId]['total']++;
                if ($q->is_right) $notes[$noteId]['right']++;
            }
        }
        $uddb->usertestsTable($this->userId)->batchInsert($insertList);

        //计算每个知识点的平均时间,保留一位小数
        foreach ($notes as &$note) {
            $note['duration'] = round($note['duration']/$note['total'], 1);
        }

        //更新已做人数
        $this->updateXingcePersonsNum();

        //更新全站统计信息
        updateUserData($this->submitArgs);

        //保存统计信息
        $this->submitExerciseRecord['summary'] = json_encode([
            'position'  => $this->getXingcePersonsNum(),
            'duration'  => (int)$this->submitArgs['duration'],
            'accuracy'  => round($right/$total, 3),
            'note_info' => array_values($notes),
            'questions' => $qSummary
        ]);
    }
}